package web;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.dbutils.DbUtils;
import pojo.User;
import service.UserService;
import service.impl.UserServiceImpl;
import utils.JDBCUtils;
import utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

public class UserServlet extends BaseServlet {
    private UserService userService = new UserServiceImpl();

    /**
     * 注销功能
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.销毁session中的用户信息（或者销毁session）
        req.getSession().invalidate();
        //2.重定向到首页(在请求重定向中 / 表示：http://localhost:8080/)
        //所以：req.getContextPath() ==> /Book ==> http://localhost:8080/Book  即首页
        resp.sendRedirect(req.getContextPath());

    }

    /**
     * 处理登录的功能
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取请求的参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //2.调用 userService.login() 登录处理业务
        User user = userService.login(new User(null, username, password, null));
        if (user == null) {
            //登录失败
            System.out.println("登录失败！");
            //把错误的信息和回显的表单项信息，保存到request域中
            req.setAttribute("msg", "用户名或密码错误！");
            req.setAttribute("username", username);
            //跳回登录页面
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req, resp);
        } else {
            //登陆成功
            System.out.println("登录成功！");
            //保存用户登录的信息到session域中
            req.getSession().setAttribute("user", user);
            //调到登录成功的页面 login_success.jsp
            req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req, resp);
        }
    }

    /**
     * 处理注册的功能
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取session中的验证码
        String token = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        //删除session中的验证码，防止下次重复使用
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);

        //1.获取请求的参数(html页面输入框内容)
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String code = req.getParameter("code");

        User user = WebUtils.copyParamToBean(req.getParameterMap(), new User());

        //2.检查验证码是否正确
        if (token != null && token.equalsIgnoreCase(code)) {
            //   正确：
            //     3.检查用户名是否可用(检查用户名是否存在于数据库中，不存在表示可用)
            //       不可用：
            if (userService.existsUsername(username)) {
                //把回显的信息保存在request域中
                req.setAttribute("msg", "用户名已存在！");
                req.setAttribute("username", username);
                req.setAttribute("email", email);

                System.out.println("用户名" + username + "已存在");
                //          跳回注册页面
                req.getRequestDispatcher("/pages/user/regist_bind(click_blur)事件.jsp").forward(req, resp);

            }
            //       可用：
            else {
                //          调用Service保存到数据库
                userService.registUser(new User(null, username, password, email));
                //          跳转到注册成功的页面 regist_success.jsp
                req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req, resp);
            }
        } else {
            //   不正确：
            //把回显的信息保存在request域中
            req.setAttribute("msg", "验证码错误！");
            req.setAttribute("username", username);
            req.setAttribute("email", email);

            System.out.println("验证码" + code + "错误");
            //   跳回注册页面
            req.getRequestDispatcher("/pages/user/regist_bind(click_blur)事件.jsp").forward(req, resp);
        }
    }

    /**
     * 验证用户名是否可用（在数据库中不存在）
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void ajaxExistsUsername(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取请求的参数username
        String username = req.getParameter("username");
        //2.调用existsUsername();判断数据库中是否存在该用户名
        boolean existsUsername = userService.existsUsername(username);
        //3.把结果保存在map集合中
        Map<String,Boolean> map = new HashMap<>();
        map.put("existsUsername",existsUsername);
        //4.将map集合转换为json字符串
        Gson gson = new Gson();
        String jsonString = gson.toJson(map);
        //5.向客户端回传数据
        resp.getWriter().print(jsonString);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
